import bcrypt from 'bcryptjs';
import StudentModel from '../model/studentModel.js';
import Result from '../common/result.js';
import { generateToken, getTokenInfo } from '../common/auth.js'

const StudentController = {
  // Get student list with pagination
  async getList(req, res) {
    try {
      if (!req.params.page || isNaN(req.params.page)) {
        req.params.page = 1;
      }
      const students = await StudentModel.getList(req.query, req.params.page);
      console.log(students);
      // Ensure return value is an array
      return Result.success(res, Array.isArray(students.list) ? students : []);
    } catch (error) {
      console.error('Get student list error:', error);
      return Result.error(res, 'Failed to get student list');
    }
  },

  // Get student by ID
  async getById(req, res) {
    const { id } = req.params;
    if (!id) {
      return Result.badRequest(res);
    }
    const student = await StudentModel.getById(id);
    if (!student) {
      return Result.notFound(res, 'Student not found');
    }
    return Result.success(res, student);
  },

  // Update student profile
  async update(req, res) {
    const { id } = req.params;
    const stuId = getTokenInfo(req.headers.authorization).id;
    
    if (stuId != id) {
      return Result.error(res, 'You are not authorized to update this student');
    }

    const student = {
      studentId: id,
      name: req.body.name,
      bio: req.body.bio,
      interests: req.body.interests,
      courses: req.body.courses,
      achievements: req.body.achievements,
      photo: req.body.photo
    };

    const result = await StudentModel.update(student);
    return Result.success(res, result);
  },

  // Delete student (soft delete)
  async delete(req, res) {
    const { id } = req.params;
    const result = await StudentModel.delete(id);
    return Result.success(res, result);
  },

  // Student login
  async login(req, res) {
    const { email, password } = req.body;
    if (!email || !password) {
      return Result.badRequest(res);
    }
    const student = await StudentModel.getByEmail(email);
    if (!student) {
      return Result.badRequest(res, 'Student not found, please register first');
    }
    const isMatch = await bcrypt.compare(password, student.Password);
    if (!isMatch) {
      return Result.badRequest(res, 'Password is incorrect');
    }
    // Generate JWT token
    const token = generateToken(student.StudentID, student.Name, student.Email);
    return Result.success(res, {
      token, 
      userInfo: {
        id: student.StudentID, 
        name: student.Name, 
        bio: student.Bio, 
        photo: student.Photo,
        email: student.Email
      }
    }, 'Login success');
  },

  // Check if email exists
  async checkEmail(req, res) {
    const { email } = req.query;
    if (!email) {
      return Result.badRequest(res);
    }
    const student = await StudentModel.getByEmail(email);
    if (student) {
      return Result.success(res, true);
    }
    return Result.success(res, false);
  },

  // Student registration
  async register(req, res) {
    const student = req.body;
    // Basic field validation
    if (!student.name || !student.email || !student.password) {
      return Result.badRequest(res, 'Name, email and password are required');
    }

    // Email format validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(student.email)) {
      return Result.badRequest(res, 'Invalid email format');
    }

    // Check if email already exists
    if (await StudentModel.getByEmail(student.email)) {
      return Result.badRequest(res, 'Email already exists');
    }

    // Password validation
    if (student.password.indexOf(' ') !== -1) {
      return Result.badRequest(res, 'Password cannot contain spaces');
    }
    if (student.password.search(/[a-z]/i) < 0 || student.password.search(/[0-9]/) < 0) {
      return Result.badRequest(res, 'Password must contain at least one letter and one number');
    }
    if (student.password.length < 6) {
      return Result.badRequest(res, 'Password must be at least 6 characters');
    }

    // Encrypt password
    student.password = await bcrypt.hash(student.password, 10);
    
    // Create student record
    const result = await StudentModel.insert(student);
    return Result.success(res, result, 'Registration successful');
  },

  // Reset password
  async resetPassword(req, res) {
    const { email, password, newPassword } = req.body;
    if (!email || !password) {
      return Result.badRequest(res);
    }
    const student = await StudentModel.getByEmail(email);
    if (!student) {
      return Result.badRequest(res, 'Student not found, please register first');
    }
    const stuId = getTokenInfo(req.headers.authorization).id;

    if (stuId != student.StudentID) {
      return Result.error(res, 'You are not authorized to update password');
    }
    const isMatch = await bcrypt.compare(password, student.Password);
    const newIsMatch = await bcrypt.compare(newPassword, student.Password);
    if (newIsMatch) {
      return Result.badRequest(res, 'New password cannot be the same as the old password');
    }
    if (!isMatch) {
      return Result.badRequest(res, 'Password is incorrect');
    }
    const pwd = await bcrypt.hash(newPassword, 10);
    const result = await StudentModel.updatePassword(student.StudentID, pwd);
    return Result.success(res, result);
  },

  // Search students
  async search(req, res) {
    try {
      const { keyword } = req.query;
      if (!keyword) {
        return Result.badRequest(res, 'Search keyword is required');
      }
      const students = await StudentModel.getList({ keyword }, 1);
      return Result.success(res, Array.isArray(students) ? students : []);
    } catch (error) {
      console.error('Search students error:', error);
      return Result.error(res, 'Failed to search students');
    }
  }
};

export default StudentController;